<template>
  <section>
    <!--顶部搜索工具条-->
    <el-card :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" @submit.native.prevent>
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="请输入搜索内容"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList">查询</el-button>
        </el-form-item>
        <el-form-item v-if="buttonFuncs.handleAdd">
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!--列表-->
    <el-table
      :data="permissions"
      v-loading="listLoading"
      row-key="Id"
      lazy
      :load="loadChildren"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      style="width: 100%"
      ref="table"
      @select="dialogCheck"
      class="custom-tbl"
    >
      <el-table-column label="菜单/按钮" width="200">
        <template #default="scope">
          <i class="fa" :class="scope.row.Icon"></i>

          {{ scope.row.Name }}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="PnameArr" label="父节点" width="" sortable>
      </el-table-column> -->
      <el-table-column prop="Code" label="路由地址" width></el-table-column>
      <el-table-column prop="MName" label="API接口" width></el-table-column>
      <el-table-column prop="OrderSort" label="Sort" width></el-table-column>
      <el-table-column prop="IsButton" label="是否按钮" width="100">
        <template #default="scope">
          <el-tag
            :type="!scope.row.IsButton ? 'success' : 'danger'"
            disable-transitions
            >{{ !scope.row.IsButton ? "否" : "是" }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="Func" label="按钮事件" width></el-table-column>
      <el-table-column prop="IsHide" label="是否隐藏" width="100">
        <template #default="scope">
          <el-tag
            :type="!scope.row.IsHide ? 'success' : 'danger'"
            disable-transitions
            >{{ !scope.row.IsHide ? "否" : "是" }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="IskeepAlive" label="keepAlive" width="100">
        <template #default="scope">
          <el-tag
            :type="!scope.row.IskeepAlive ? 'success' : 'danger'"
            disable-transitions
            >{{ !scope.row.IskeepAlive ? "否" : "是" }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right">
        <template #default="scope">
          <div v-for="item in operateButtons" v-bind:key="item.id">
            <el-button link type="primary" size="small" @click="callFunction(item, scope.row)">{{item.name}}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination
        layout="prev, pager, next"
        @current-change="handleCurrentChange"
        :page-size="50"
        :total="total"
        style="float: right"
      ></el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog
      title="编辑"
      v-model="editFormVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="editForm"
        label-width="80px"
        :rules="editFormRules"
        ref="editForm"
      >
        <el-form-item label="菜单名称" prop="Name">
          <el-input v-model="editForm.Name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="菜单类型">
          <el-radio-group @change="clkType" v-model="editForm.MenuType">
            <el-radio label="folder">目录</el-radio>
            <el-radio label="page">页面</el-radio>
            <el-radio label="button">按钮</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="路由地址" prop="Code">
          <el-tooltip placement="top">
            <template #content>
              如果是目录，请填‘-’字符
              <br />如果是按钮，请输入空格即可
              <br />如果是外链，请带上协议，比如 https://www.baidu.com
              <br />
            </template>
            <el-input
              v-model="editForm.Code"
              :disabled="editCodeDisabled"
              auto-complete="off"
            ></el-input>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="描述" prop="Description">
          <el-input
            v-model="editForm.Description"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="Icon" prop="Icon">
          <el-input v-model="editForm.Icon" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="Enabled">
          <el-select v-model="editForm.Enabled" placeholder="请选择状态">
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.Name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="排序" prop="OrderSort">
          <el-input
            type="number"
            v-model="editForm.OrderSort"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item prop="IsButton" label="是否按钮" width sortable>
          <el-switch v-model="editForm.IsButton"></el-switch>
        </el-form-item>
        <el-form-item label="按钮事件" prop="Func">
          <el-tooltip
            class="item"
            effect="dark"
            content="只写方法名即可，不用带括号，比如：handleEdit"
            placement="top-start"
          >
            <el-input v-model="editForm.Func" auto-complete="off"></el-input>
          </el-tooltip>
        </el-form-item>
        <el-form-item prop="IsHide" label="是否隐藏" width sortable>
          <el-switch v-model="editForm.IsHide"></el-switch>
        </el-form-item>
        <el-form-item prop="IskeepAlive" label="keepAlive" width sortable>
          <el-switch v-model="editForm.IskeepAlive"></el-switch>
        </el-form-item>
        <el-form-item prop="PidArr" label="父级菜单" width sortable>
          <el-cascader
            placeholder="请选择，支持搜索功能"
            style="width: 400px"
            v-model="editForm.PidArr"
            :options="options"
            filterable
            :key="isResouceShow"
            :props="{ checkStrictly: true, expandTrigger: 'hover' }"
            v-if="!editLoading"
          ></el-cascader>
          <el-cascader
            placeholder="加载中..."
            style="width: 400px"
            v-if="editLoading"
          ></el-cascader>
        </el-form-item>
        <el-form-item prop="Mid" label="API接口" width sortable>
          <el-select
            style="width: 100%"
            v-model="editForm.Mid"
            placeholder="请选择API"
          >
            <el-option :key="0" :value="0" :label="'无需api'"></el-option>
            <el-option
              v-for="item in modules"
              :key="item.Id"
              :value="item.Id"
              :label="item.LinkUrl"
            >
              <span style="float: left">{{ item.LinkUrl }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.Name
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click.native="editCancel">取消</el-button>
          <el-button
            type="primary"
            @click.native="editSubmit"
            :loading="editLoading"
            >提交</el-button
          >
        </div>
      </template>
      
    </el-dialog>

    <!--同步界面-->
    <el-dialog
      title="菜单接口同步"
      v-model="syncFormVisible"
    >
      <el-table
        :data="syncoptions"
        row-key="Name"
        style="width: 100%"
        ref="table1"
      >
        <el-table-column type="index" width="70"></el-table-column>
        <el-table-column prop="Name" label="菜单名" width></el-table-column>
        <el-table-column prop="MName" label="API接口" ></el-table-column>
        <el-table-column prop="IsButton" label="是否按钮" width="90">
          <template #default="scope">
            <el-tag
              :type="!scope.row.IsButton ? 'success' : 'danger'"
              disable-transitions
              >{{ !scope.row.IsButton ? "否" : "是" }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="Pid" label="父Id"  width="90"></el-table-column>
      </el-table>
      <template #footer>
        <div  class="dialog-footer">
          <el-button @click.native="syncFormVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click.native="handleSync(true)"
            >确定同步</el-button
          >
        </div>
      </template>
      
    </el-dialog>
  </section>
</template>

<script>

import {
  getPermissionTreeTable,
  removePermission,
  editPermission,
  getPermissionTree,
  getModuleListPage,
  migratePermissionTable
} from "/@/api/system";
import { getButtonMap } from "/@/router/backEnd";
import { ElMessage} from 'element-plus'

export default {
  data() {
    return {
      syncoptions: [],
      operateButtons: [],
      buttonFuncs: {},
      currentRow: null,
      isResouceShow: 0,
      filters: {
        keyword: "",
      },
      options: [],
      permissions: [],
      modules: [], //接口api列表
      statusList: [
        { Name: "激活", value: true },
        { Name: "禁用", value: false },
      ],
      total: 0,
      page: 1,
      listLoading: false,
      sels: [], //列表选中列
      addDialogFormVisible: false,
      editFormVisible: false, //编辑界面是否显示
      editLoading: false,
      editFormRules: {
        Name: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
        Code: [{ required: true, message: "请输入路由地址", trigger: "blur" }],
        PidArr: [{ required: true, message: "请选择父级菜单", trigger: "blur" }],
      },
      //编辑界面数据
      editForm: {
        Id: 0,
        Mid: 0,
        OrderSort: 0,
        PidArr: [],
        CreateBy: "",
        Name: "",
        Code: "",
        Description: "",
        Icon: "",
        Func: "",
        Enabled: true,
        IsButton: false,
        IsHide: false,
        IskeepAlive: false,
      },

      addFormVisible: false, //新增界面是否显示
      addLoading: false,
      addCodeDisabled: false,
      editCodeDisabled: false,
      syncFormVisible: false,
      loadMap: new Map(),
    }
  },
  methods: {
    dialogCheck(selection, row) {
      this.currentRow = null;
      this.$refs.table.clearSelection();
      if (selection.length === 0) {
        return;
      }
      if (row) {
        this.selectCurrentRow(row);
      }
    },
    selectCurrentRow(val) {
      if (val) {
        this.currentRow = val;
        this.$refs.table.clearSelection();
        this.$refs.table.toggleRowSelection(val, true);
      }
    },
    editCancel() {
      this.editFormVisible = false;
      this.editLoading = false;
      this.editForm = {Index:0};
    },
    addCancel() {
      this.addFormVisible = false;
      this.addLoading = false;
      this.addForm = {Index:0};
    },
    setClkType(){
      if (this.editForm.IsButton) {
        this.editCodeDisabled = true;
        this.editForm.MenuType = "button";
      } else if (this.editForm.Code == "-") {
        this.editCodeDisabled = true;
        this.editForm.MenuType = "folder";
      } else {
        this.editForm.MenuType = "page";
        this.editCodeDisabled = false;
      }
    },
    clkType() {
      this.editForm.IsButton = false;
      this.editCodeDisabled = false;
      if (this.editForm.MenuType == "page") {
        this.editForm.Code = "";
      } else if (this.editForm.MenuType == "folder") {
        this.editForm.Code = "-";
        this.editCodeDisabled = true;
      } else if (this.editForm.MenuType == "button") {
        this.editForm.Code = " ";
        this.editForm.IsButton = true;
        this.editCodeDisabled = true;
      }
    },
    callFunction(item, row) {
      this[item.Func].call(this, row);
    },
    //显示转换
    formatEnabled: function (row) {
      return row.Enabled ? "正常" : "未知";
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getList();
    },
    loadChildren(tree, treeNode, resolve) {
      let para = {
        page: this.page,
        f: tree.Id,
        key: this.filters.keyword,
      };

      if (!this.loadMap.has(tree.id)) {
        this.loadMap.set(tree.Id, {tree, treeNode, resolve})
      }
      getPermissionTreeTable(para).then((res) => {
        resolve(res.data);
      });
    },
    refreshChildren(pid){
      
      // this.$set(this.$refs["table"].store.states, "lazyTreeNodeMap", {});
      // this.$set(this.$refs["table"].store.states, "treeData", {});
      //treeData[id]中的id就是需要展开节点的table定义的rowkey属性值
      if (pid > 0){
        const {tree, treeNode, resolve} = this.loadMap.get(pid);
        this.loadChildren(tree, treeNode, resolve)
      }
      
    },
    //获取用户列表
    getList() {
      let para = {
        page: this.page,
        key: this.filters.keyword,
      };
      this.listLoading = true;

      //NProgress.start();
      getPermissionTreeTable(para).then((res) => {
        this.permissions = res.data;
        this.listLoading = false;
        //NProgress.done();
      });
    },
    //删除
    handleDel(row) {
      this.$confirm("确认删除该记录吗?", "提示", {
        type: "warning",
      })
        .then(() => {
          this.listLoading = true;
          //NProgress.start();
          let para = { id: row.Id };
          removePermission(para).then((res) => {
            this.listLoading = false;
            //NProgress.done();
            if (res.success) {
              ElMessage({
                message: "删除成功",
                type: "success",
              });
            } else {
              ElMessage({
                message: res.msg,
                type: "error",
              });
            }

            this.getPermissions();
            this.refreshChildren(row.Pid)
          });
        })
        .catch(() => {});
    },
    //显示编辑界面
    handleEdit(row) {
      let that = this;

      that.options = [];

      that.editLoading = true;
      that.editCodeDisabled = false;
      let para = { pid: row.Id };
      getPermissionTree(para).then((res) => {
        ++that.isResouceShow;
        this.options.push(res.data);
        that.editForm = Object.assign({}, row);
        this.setClkType();
        that.editLoading = false;
        that.editFormVisible = true;
      });
    },
    //显示同步界面
    handleSync(isAction = false) {
      let row = this.currentRow;
      var pid = row && row.Id;
      if (!(pid > 0)) {
        ElMessage({
          message: "请选择要同步的父级页面！",
          type: "error",
        });

        return;
      }

      var controllerName = row && row.MName && row.MName.split('/')[2] || '';
      if (!controllerName) {
        ElMessage({
          message: "要同步的接口控制器名不能为空！",
          type: "error",
        });

        return;
      }

      let that = this;

      that.syncoptions = [];

      that.syncFormVisible = true;
      let para = { controllerName, pid, isAction };
      migratePermissionTable(para).then((res) => {
        that.syncoptions = res.data;
      });
    },
    //显示新增界面
    handleAdd() {
      let that = this;
      this.options = [];
      this.editForm = {};
      this.editLoading = true;
      this.editFormVisible = true;
      this.editCodeDisabled = false;

      let para = { pid: 0 };
      getPermissionTree(para).then((res) => {
        ++this.isResouceShow;
        this.options.push(res.data);
        that.editForm = Object.assign({});
        this.setClkType();
        that.editLoading = false;
      });
    },
    //编辑
    editSubmit: function () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.editForm);
            para.Pid = para.PidArr.pop();

            if (para.Id == para.Pid) {
              ElMessage({
                message: "警告，父节点不能是自己！",
                type: "error",
              });

              this.editLoading = false;
              return;
            }

            editPermission(para).then((res) => {

              this.editLoading = false;
              if (res.success) {
                this.editLoading = false;
                //NProgress.done();
                ElMessage({
                  message: res.msg,
                  type: "success",
                });
                this.$refs["editForm"].resetFields();
                this.$refs.table.setCurrentRow();
                this.editFormVisible = false;
                this.getPermissions();
                this.refreshChildren(para.Pid)
              } else {
                ElMessage({
                  message: res.msg,
                  type: "error",
                });
              }
            });
          });
        }
      });
    },
  },
  mounted() {
    this.getList();
    let buttonMap = getButtonMap(this.$route.path);
    this.buttonFuncs = buttonMap['buttonFuncs']|| [];
    this.operateButtons = buttonMap['operation'] || [];

    getModuleListPage({ page: -1 }).then((res) => {
      this.modules = res.data.data;
    });

  },
};
</script>

<style scoped>
.custom-tbl :deep() .has-gutter .el-checkbox {
  display: none;
}
</style>
